import React from 'react';
import { connect } from 'dva';
import { message } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BatchUpload from '../../components/BatchUpload/Index';
import FileUpload from '../../components/BatchUpload/Upload';
import Finish from '../../components/BatchUpload/Finish';

@connect(({ card, loading, card: { fileId, fileName } }) => ({
  uploading: loading.effects['publicdata/uploadFile'],
  batchQuery: card.batchQuery,
  fileId,
  fileName,
}))
class GrantBatch extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      currentStep: 0,
      showProgress: true,
      progressVisible: false,
      resultInfo: {
        // 结果数据必传
        batchName: '', // 任务名称
        taskCount: 0, // 导入数据
        successCount: 0, // 成功数据
        errorCount: 0, // 失败数据
        batchNo: '', // 批次号
        errorUrl: '/esApi/insCardHdl/downloadExcelErrData', // 下载错误信息地址
        errorParams: null, // 下载错误数据参数
      },
    };
  }

  // 设置当前位置
  setCurrentstep = currentStep => {
    this.setState({ currentStep });
  };

  // 获取
  componentDidMount = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'card/fetchTemplate',
      payload: {
        tempSerType: 26, // 批量发放
      },
    });
  };

  // 下一步
  onNext = () => {
    const {
      dispatch,
      form: { validateFields },
    } = this.props;
    const { currentStep } = this.state;
    validateFields((err, values) => {
      if (!err) {
        dispatch({
          type: 'addemp/getDownloadInfo',
          payload: {
            ...values,
          },
        });
      }
    });
    this.setCurrentstep(currentStep + 1);
  };

  // 上传文件：需要携带参数即传：batchQuery
  uploadFile = formData => {
    const { dispatch } = this.props;
    const { currentStep, showProgress, resultInfo } = this.state;

    dispatch({
      type: 'publicdata/uploadFile',
      uploadUrl: '/esApi/insCardHdl/uploadExcelIssue',
      payload: formData,
      callback: data => {
        if (showProgress) {
          // 需要展示进度
          // 获取文件批次号
          this.handleModalVisible(showProgress);
          if (data.success) {
            const interval = setInterval(() => {
              dispatch({
                type: 'card/getUploadProgress',
                payload: { batchId: data.batchNo },
                callback: res => {
                  // 获取文件批次号
                  if (!res.data || res.data.successProp === 100) {
                    // 上传完成
                    clearInterval(interval);
                    setTimeout(() => {
                      dispatch({
                        type: 'card/updateQuery',
                        payload: { progressPercent: 0 },
                      });
                      this.handleModalVisible();
                      resultInfo.errorParams = {
                        batNo: data.batchNo,
                      };
                      this.setState({
                        currentStep: currentStep + 1,
                        resultInfo: { ...resultInfo, ...res.data, batchName: '批量发放' },
                      });
                    }, 2000);
                  } else if (!res.success) {
                    // 服务端异常
                    clearInterval(interval);
                    message.warning(`${res.message || '上传失败'}`);
                  }
                },
              });
            }, 2000);
          }
        } else {
          // 直接获取结果
          const temp = data;
          temp.errorParams = { batNo: temp.batchNo };
          this.setState({
            resultInfo: { ...resultInfo, ...temp, batchName: '批量发放' },
            currentStep: currentStep + 1,
          });
        }
      },
    });
  };

  // 进度条模态框显隐
  handleModalVisible = flag => {
    this.setState({
      progressVisible: !!flag,
    });
  };

  render() {
    const { fileId, fileName, uploading, batchQuery } = this.props;
    const { currentStep, resultInfo, progressVisible, showProgress } = this.state;
    return (
      <PageHeaderWrapper>
        <BatchUpload currentStep={currentStep}>
          <FileUpload
            title="上传文件"
            currentStep={currentStep}
            setCurrentstep={this.setCurrentstep}
            downloadTempInfo={{
              // 下载模板信息
              params: {
                fileId,
                fileName,
              },
              url: '/esApi/fileServer/downloadFile',
              type: 'GET',
            }}
            uploadFile={this.uploadFile}
            uploading={uploading}
            // 展示进度条需要的数据
            showProgress={showProgress}
            progressPercent={batchQuery.progressPercent}
            progressTitle="批量发放"
            progressVisible={progressVisible}
            handleModalVisible={this.handleModalVisible}
          />
          <Finish title="完成" resultInfo={resultInfo} setCurrentstep={this.setCurrentstep} />
        </BatchUpload>
      </PageHeaderWrapper>
    );
  }
}

export default GrantBatch;
